package com.example.sangong.interceptor;

import com.example.sangong.utils.MyLocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
@Slf4j
public class RequestLogInterceptor implements HandlerInterceptor {
    private static ThreadLocal<LocalDateTime> starTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        starTime.set(now);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LocalDateTime startTime = starTime.get();
        LocalDateTime now = LocalDateTime.now();
        log.error("方法开始的时间为:{},执行完成的时间为：{},耗时为{}毫秒", startTime.toLocalTime(), now.toLocalTime(), MyLocalDateTimeUtils.minus(startTime, now));
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
